var HxBasicGoodsInfoDlg = {
    data: {
		id:"",
        goodsCustomerId: "",
        goodsCustomerName: "",
        goodsName: "",
        goodsNumber: "",
        goodsPcode69: "",
        goodsXcode69: "",
        goodsHelpcode: "",
        goodsSpecs: "",
        goodsBigtype: "",
        goodsBrand: "",
        jibenUnit: "",
        kcUnit: "",
        kcRate: "",
        cgUnit: "",
        cgRate: "",
        pfUnit: "",
        pfRate: "",
        psUnit: "",
        psRate: "",
        anquanNum: "",
        goodsBottom: "",
        goodsLamination: "",
        goodsTraylayer: "",
        goodsSupportvolume: "",
        length: "",
        height: "",
        width: "",
        goodsWeight: "",
        goodsVolume: "",
        goodsChargingCg: "",
        goodsChargingPs: "",
        goodsChargingPf: "",
        goodsWarranty: ""
    }
};
var BasicPutgoodsInfoDlg = {
    data: {
		id:"",
		dictId:"",
        putgoodsCustomerId: "",
        putgoodsOperateName: "",
        putgoodsName: "",
		unitNumber:"",
		unitType:""
    }
};
var submit = 2
layui.use(['table', 'admin', 'ax','laydate'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var laydate = layui.laydate;

    laydate.render({
    	elem:'#startTime'
        	,value:new Date()
    });
    
    laydate.render({
    	elem:'#endTime'
        	,value:new Date()
    });

    /**
     * 入库订单表管理
     */
    var HxOrderPut = {
        tableId: "hxOrderPutTable"
    };

    /**
     * 入库订单明细表管理
     */
    var HxOrderPutDetailed = {
        tableId: "hxOrderPutDetailedTable"
    };
    var sl = {
        goodsNum: "",
        putNum: "",
        putVolume: "",
    };

    // 发送 AJAX 请求获取合计数据
    $.ajax({
        url:Feng.ctxPath + '/hxOrderPut/count',
        dataType: "json",
        async: false,
        type: "post",
        success: function (data) {
            console.log(data);
            sl = data.data;
            console.log(sl);
        },
        error: function (xhr, status, error) {
            console.error("请求失败：", status, error);

        }
    });
    /**
     * 初始化表格的列
     */
    HxOrderPut.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: '主键'},
            {align: 'center', toolbar: '#tableBar', title: '操作'},
            {field: 'customerName', sort: true, title: '客户名称'},
            {field: 'orderState', sort: true, title: '单据状态'},
            {field: 'yuyueTime', sort: true, title: '预约时间'},
            {field: 'orderPutNumber', sort: true, title: '订单号', width: 140},
            {field: 'orderType', sort: true, title: '单据类型'},
            {field: 'getWarehouse', sort: true, title: '收货仓库'},
            {field: 'setUnit', sort: true, title: '发货客户', width: 140, totalRowText: '合计：'},
            {field: 'goodsNum', sort: true, title: '商品数',totalRowText: sl.goodsNum},
            {field: 'putNum', sort: true, title: '数量', totalRowText: sl.putNum},
            {field: 'putVolume', sort: true, title: '体积',totalRowText: sl.putVolume},
            {field: 'contacts', sort: true, title: '联系人'},
            {field: 'tel', sort: true, title: '联系电话'},
            {field: 'createUserName', sort: true, title: '创建人'},
            {field: 'revokeUserName', sort: true, title: '撤回人'},
            {field: 'createTime', sort: true, title: '创建时间'},
            {field: 'revokeTime', sort: true, title: '撤回时间'},
            {field: 'notes', sort: true, title: '备注'},
        ]];
    };

    /**
     * 点击查询按钮
     */
    HxOrderPut.search = function () {


        // 重新加载表格
        var queryData = {};
        queryData['timeType'] = $("#timeType").val();
        queryData['startTime'] = $("#startTime").val();
        queryData['endTime'] = $("#endTime").val();
        queryData['orderState'] = $("#orderState").val();
        queryData['customerId'] = $("#customerId").val();
        queryData['getWarehouseId'] = $("#getWarehouseId").val();
        queryData['setUnits'] = $("#setUnit").val();
        queryData['condition'] = $("#condition").val();
        queryData['orderType'] = $("#orderType").val();
        queryData['goodsName'] = $("#goodsName").val();
        // table.reload(HxOrderPut.tableId, {
        //     where: queryData,
        //     page: {curr: 1},
        //     done: function () {
        //
        //     }
        // });
        $.ajax({
            url:Feng.ctxPath + '/hxOrderPut/count',
            data: queryData, // 将 queryData 作为请求体发送
            dataType:"json",   //返回格式为json
            async: false,
            type:"post",   //请求方式
            success:function(data){
                sl = data.data
                console.log(data);
            }
        });
        var tableResult = table.render({
            elem: '#' + HxOrderPut.tableId,
            where: queryData,
            url: Feng.ctxPath + '/hxOrderPut/list',
            toolbar: '#toolbarfrom',
            totalRow: true ,//开启合计行
            cellMinWidth: 100,
            cols: HxOrderPut.initColumn(),
            parseData: function(res){ // 数据转换
                console.log(res);
                return {
                    "code": 0,
                    "msg": res.msg, // 假设原数据中的msg字段存储的是提示信息
                    "count": res.count,
                    "data": $.map(res.data, function(item){ // 假设原数据中的data字段存储的是数据集
                        return {
                            // 假设你想转换的字段是numberField
                            putNum: Number(item.putNum), // 将字符串转换为数字
                            // 其他字段保持不变
                            putVolume: item.putVolume,
                            id: item.id,
                            putWeight: item.putWeight,
                            goodsNum: item.goodsNum,
                            putMoney: item.putMoney,
                            detailedDate: item.detailedDate,
                            customerName: item.customerName,
                            orderState: item.orderState,
                            yuyueTime: item.yuyueTime,
                            orderType: item.orderType,
                            getWarehouse: item.getWarehouse,
                            orderPutNumber: item.orderPutNumber,
                            contacts: item.contacts,
                            tel: item.tel,
                            createUserName: item.createUserName,
                            revokeUserName: item.revokeUserName,
                            createTime: item.createTime,
                            revokeTime: item.revokeTime,
                            notes: item.notes,
                            setUnit: item.setUnit,
                        };
                    })
                };
            },
            page: true,
            limit: 40,
            height: 410,
        });
    };


    // 导入excel
	 $('#btnExpimport').click(function () {
        layer.open({
            type: 2,
            title: '入库订单导入',
            area: ['1000px', '600px'],
            anim: 5,
            content: Feng.ctxPath + '/hxOrderPut/toimportExcel',
            end: function () {
                table.reload(HxOrderPut.tableId);
            }
        });
	 });

    // 导入excel
    $('#btnExpimportKh').click(function () {
        layer.open({
            type: 2,
            title: '多点入库订单导入',
            area: ['1000px', '600px'],
            anim: 5,
            content: Feng.ctxPath + '/hxOrderPut/toimportKhExcel',
            end: function () {
                table.reload(HxOrderPut.tableId);
            }
        });
    });


    // 批量打印点击事件
    $('#btnPrint').click(function () {
        var checkStatus = table.checkStatus(HxOrderPut.tableId);
        var data2 = checkStatus.data;
        if (data2.length>0) {
            var ids = [];
            for (var i = 0; i < data2.length; i++) {
                ids.push(data2[i].id);
            }
            layer.open({
                type: 2,
                title: '批量打印入库订单',
                area: ['990px', '550px'],
                anim: 5,
                content: Feng.ctxPath + '/hxOrderPut/print?ids='+ids,
                end: function () {
                }
            });
        } else {
            layer.alert('请至少选中一条数据');
        }
    });




    // 拉取新零帮预约任务
    $('#yuyuelaqu').click(function () {
        layer.open({
            type: 2,
            title: '拉取入库申请单',
            area: ['990px', '550px'],
            anim: 5,
            content: Feng.ctxPath + '/hxOrderPut/xlbYuyue',
            end: function () {
                table.reload(HxOrderPut.tableId);
            }
        });
    });


    // 拉取tcsl入库申请单
    $('#pullTcslOrder').click(function () {
        layer.open({
            type: 2,
            title: '拉取tcsl入库申请单',
            area: ['990px', '550px'],
            anim: 5,
            content: Feng.ctxPath + '/hxOrderPut/tcslYuyue',
            end: function () {
                table.reload(HxOrderPut.tableId);
            }
        });

    });

    // 预约确认
    $('#yuyue').click(function () {
        var checkStatus = table.checkStatus('hxOrderPutTable');
        data = checkStatus.data;
        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
                ids.push(data[i].id);
            }
            console.log(ids);
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/hxOrderPut/confirmxlb?ids="+ids, function (data) {
                    if(data.success){
                        Feng.success("预约确认成功!");
                        table.reload(HxOrderPut.tableId);
                    } else {
                        Feng.error("预约确认失败!" + data.message + "!");
                    }
                }, function (data) {
                    Feng.error("预约确认失败!" + data.responseJSON.message + "!");
                });
                ajax.start();
            };
            Feng.confirm("是否确认选中订单?", operation);
        } else {
            layer.alert('请至少选中一条数据');
        }
    });



    //点击选择商品名称
    $('#choiceGoods').click(function () {
        layer.open({
            type: 2,
            title: '选择商品',
            area: ['1000px', '500px'],
            content: Feng.ctxPath + '/hxBasicGoods/toChoiceGoods',
            end: function () {
                $("#goodsName").val(HxBasicGoodsInfoDlg.data.goodsName);//商品名称
            }
        });
    });
    
    $('#choiceSetUnit').click(function () {
        layer.open({
            type: 2,
            title: '选择单位',
            area: ['1000px', '500px'],
            content: Feng.ctxPath + '/basicPutgoods/tochoiceBasicPutgoods_hx',
            end: function () {
                $("#setUnit").val(BasicPutgoodsInfoDlg.data.putgoodsName);
            }
        });
    });

    /**
     * 弹出添加对话框
     */
    HxOrderPut.openAddDlg = function () {
        window.location.href = Feng.ctxPath + '/hxOrderPut/add';
    };

    /**
     * 导出excel按钮
     */
    HxOrderPut.exportExcel = function () {
        var checkRows = table.checkStatus(HxOrderPut.tableId);
        if (checkRows.data.length > 0) {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        } else {
            var queryData = {};
            queryData['timeType'] = $("#timeType").val();
            queryData['startTime'] = $("#startTime").val();
            queryData['endTime'] = $("#endTime").val();
            queryData['orderState'] = $("#orderState").val();
            queryData['customerId'] = $("#customerId").val();
            queryData['getWarehouseId'] = $("#getWarehouseId").val();
            queryData['setUnits'] = $("#setUnit").val();
            queryData['condition'] = $("#condition").val();
            queryData['orderType'] = $("#orderType").val();
            queryData['goodsName'] = $("#goodsName").val();

            $.ajax({
                type: "POST",
                url: Feng.ctxPath + "/hxOrderPut/listAll",
                dataType:'json',
                data: queryData,
                beforeSend: function () {
                    //弹出加载中
                    index = layer.load(1, {
                        shade: [0.3, '#000'] //0.1透明度的白色背景
                    });
                },
                success: function (data) {
                    checkRows.data = data;
                    table.exportFile(tableResult.config.id, checkRows.data, 'xls');                    layer.close(index);
                },
                error: function (data) {
                    console.log(data)
                }
            });
        }
    };

    /**
     * 点击编辑
     *
     * @param data 点击按钮时候的行数据
     */
    HxOrderPut.openEditDlg = function (data) {
        window.location.href = Feng.ctxPath + '/hxOrderPut/edit?id=' + data.id;
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + HxOrderPut.tableId,
        url: Feng.ctxPath + '/hxOrderPut/list',
        toolbar: '#toolbarfrom',
        totalRow: true ,//开启合计行
        cellMinWidth: 100,
        cols: HxOrderPut.initColumn(),
        parseData: function(res){ // 数据转换
            console.log(res);
            return {
                "code": 0,
                "msg": res.msg, // 假设原数据中的msg字段存储的是提示信息
                "count": res.count,
                "data": $.map(res.data, function(item){ // 假设原数据中的data字段存储的是数据集
                    return {
                        // 假设你想转换的字段是numberField
                        putNum: Number(item.putNum), // 将字符串转换为数字
                        //其他字段保持不变
                        id: item.id,
                        putVolume: item.putVolume,
                        putWeight: item.putWeight,
                        goodsNum: item.goodsNum,
                        putMoney: item.putMoney,
                        detailedDate: item.detailedDate,
                        customerName: item.customerName,
                        orderState: item.orderState,
                        yuyueTime: item.yuyueTime,
                        orderType: item.orderType,
                        getWarehouse: item.getWarehouse,
                        orderPutNumber: item.orderPutNumber,
                        contacts: item.contacts,
                        tel: item.tel,
                        createUserName: item.createUserName,
                        revokeUserName: item.revokeUserName,
                        createTime: item.createTime,
                        revokeTime: item.revokeTime,
                        notes: item.notes,
                        setUnit: item.setUnit,
                    };
                })
            };
        },
        page: true,
        limit: 40,
        height: 410,
    });

     // 批量提交
     $('#btnSubmission').click(function () {
    	var checkStatus = table.checkStatus('hxOrderPutTable');
        data = checkStatus.data;
        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
            	ids.push(data[i].id);
			}
			
            layer.confirm('是否提交选中订单?', function(index){
            	layer.close(index);
            	var msg;
                $.ajax({
                	url:Feng.ctxPath + "/hxOrderPut/submission?ids="+ids,
                	cache: false,
                	dataType:"json",
                	beforeSend:function(){
                		msg = layer.msg('提交中。。。请耐心等待', {
                			  icon: 16,
                			  shade: [0.2,'#000'], //0.1透明度的白色背景
                			  time: false
                		});
                	},
                	success:function(data){
                    	layer.close(msg); 
                		if (data.success) {
                        	Feng.success("提交成功!");
                			table.reload(HxOrderPut.tableId);
						} else {
							if (data.message !=null &&data.message!='') {
			    				var msg2 =  layer.open({
				  					  title: '提示' ,
				  					  content: data.message,
				  					  btn: ['确定'],
				  					  yes: function (){
				  						  	layer.close(msg2);
                							table.reload(HxOrderPut.tableId);
				  					  }
			    				});     
							} else {
	  		                    Feng.error("提交失败！");
                				table.reload(HxOrderPut.tableId);
							}
						}
                	},
                	error:function(data){
                    	layer.close(msg); 
                        Feng.error("提交失败！" + data.responseJSON.message)
                		table.reload(HxOrderPut.tableId);
                	}
                })
            }); 
		} else {
			layer.alert('请至少选中一条数据');
		}
     });

     // 批量作废
     $('#btnTovoid').click(function () {
    	var checkStatus = table.checkStatus('hxOrderPutTable');
        data = checkStatus.data;
        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
            	ids.push(data[i].id);
			}
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/hxOrderPut/tovoid?ids="+ids, function (data) {
                    Feng.success("作废成功!");
                	table.reload(HxOrderPut.tableId);
                }, function (data) {
                    Feng.error("作废失败!" + data.responseJSON.message + "!");
                });
                ajax.start();
            };
            Feng.confirm("是否作废选中订单?", operation);
		} else {
			layer.alert('请至少选中一条数据');
		}
     });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        HxOrderPut.search();
    });

    $('#reset').click(function () {
        $("#setUnit").val("")
        $("#condition").val("")
        $("#goodsName").val("")
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        HxOrderPut.openAddDlg();
    });

    // 导出excel
    $('#btnExp').click(function () {
        HxOrderPut.exportExcel();
    });

    // 工具条点击事件
    table.on('tool(' + HxOrderPut.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            HxOrderPut.openEditDlg(data);
        } else if (layEvent === 'toConfirm') {
           // 预约确认
			submit = 2;
	        layer.open({
	            type: 2,
	            title: '确认',
	            area: ['600px', '500px'],
	            content: Feng.ctxPath + '/hxOrderPut/toConfirm?id='+data.id,
	            end: function () {
					if(submit == 1){
                		table.reload(HxOrderPut.tableId);
					}
	            }
	        });
        } 
    });

    /**
     * 初始化表格的列
     */
    HxOrderPutDetailed.initColumn = function () {
        return [[
            {field: 'id', hide: true, title: '主键'},
            {align: 'center', toolbar: '#tableBarDetailed', title: '操作', width: 120},
            {field: 'goodsName', sort: true, title: '商品名称', width: 160},
            {field: 'goodsNumber', sort: true, title: '商品编号'},
            {field: 'goodsPcode69', sort: true, title: '商品码'},
            {field: 'goodsSpecs', sort: true, title: '规格'},

            {field: 'unit', sort: true, title: '单位', totalRowText: '合计：'},
            {field: 'num', sort: true, title: '数量', totalRow: true},
            {field: 'zpNum', sort: true, title: '赠品数量', totalRow: true},
            {field: 'sumNum', sort: true, title: '总数量', totalRow: true},
            {field: 'jibenUnit', sort: true, title: '基本单位'},
            {field: 'zpJibenNum', sort: true, title: '赠品基本数量', totalRow: true},
            {field: 'jibenNum', sort: true, title: '总基本数量', totalRow: true},

            {field: 'goodsVolume', sort: true, title: '体积'},
            {field: 'putVolume', sort: true, title: '应入体积', totalRow: true},
            {field: 'goodsWeight', sort: true, title: '重量'},
            {field: 'putWeight', sort: true, title: '应入重量', totalRow: true},
            {field: 'goodsPrice', sort: true, title: '单价'},
            {field: 'putMoney', sort: true, title: '金额', totalRow: true},
            {field: 'xlbOrderPutNumber', sort: true, title: '新零帮入库订单关联发货单单号'},
            {field: 'detailedDate', sort: true, title: '生产日期'},
            {field: 'notes', sort: true, title: '备注'},
        ]];
    };

    // 单击行事件
    table.on('row(' + HxOrderPut.tableId + ')', function (obj) {
        var data = obj.data;
		$('div[lay-id="' + HxOrderPut.tableId + '"]').find(".layui-table-body tr ").attr({ "style": "background:#FFFFFF" });//其他tr恢复原样
		$('div[lay-id="' + HxOrderPut.tableId + '"]').find(obj.tr.selector).attr({ "style": "background:#e6e6e6" });//改变当前tr颜色
        hxOrderPut(data);
    });


    function hxOrderPut(data){
    	var orderPutNumber;
    	if (data!=null) {
    		orderPutNumber = data.orderPutNumber;
		} else {
			orderPutNumber = '0';
		}
        // 渲染商品明细表格
        var tableResult = table.render({
            elem: '#' + HxOrderPutDetailed.tableId,
            url: Feng.ctxPath + '/hxOrderPutDetailed/list?orderPutNumber=' + orderPutNumber,
            page: true,
            limit: 30,
            height: 400,
            toolbar: '#toolbarfromDetailed',
            cellMinWidth: 100,
            totalRow: true ,//开启合计行
            cols: HxOrderPutDetailed.initColumn()

        });

        /**
         * 点击查询按钮
         */
    	HxOrderPutDetailed.search = function () {
            var queryData = {};
            queryData['condition'] = $("#condition2").val();
            table.reload(HxOrderPutDetailed.tableId, {
                where: queryData, page: {curr: 1},
                 done:function () {
                     // 搜索按钮点击事件
                     $('#btnSearchDetailed').click(function () {
                    	 HxOrderPutDetailed.search();
                     });
			        $('#btnAddDetailed').click(function () {
			        	HxOrderPutDetailed.addDetailed();
			        });
                }
            });
        };

    	HxOrderPutDetailed.addDetailed = function () {
            layer.open({
                type: 2,
                title: '明细录入',
                area: ['1050px', '750px'],
                anim: 5,
                content: Feng.ctxPath + '/hxOrderPutDetailed/add?orderPutNumber=' + data.orderPutNumber,
                end: function () {
                	hxOrderPut(data);
                }
            });
        };

        // 工具条点击事件
        table.on('tool(' + HxOrderPutDetailed.tableId + ')', function (obj) {
            var data2 = obj.data;
            var layEvent = obj.event;

            if (layEvent === 'editDetailed') {
                HxOrderPutDetailed.openEditDlg(data2);
            } else if (layEvent === 'deleteDetailed') {
                HxOrderPutDetailed.onDeleteItem(data2);
            }
        });

        // 修改按钮点击事件
        HxOrderPutDetailed.openEditDlg = function (data2) {
            layer.open({
                type: 2,
                title: '明细修改',
                area: ['1050px', '750px'],
                anim: 5,
                content: Feng.ctxPath + '/hxOrderPutDetailed/edit?id='+data2.id+'&goodsId='+data2.goodsId,
                end: function () {
                	hxOrderPut(data);
                }
            });
        };

        // 删除按钮点击事件
        HxOrderPutDetailed.onDeleteItem = function (data2) {
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/hxOrderPutDetailed/delete", function (data2) {
                    Feng.success("删除成功!");
                	hxOrderPut(data);
                }, function (data) {
                    Feng.error("删除失败!" + data2.responseJSON.message + "!");
                });
                ajax.set("id", data2.id);
                ajax.start();
            };
            Feng.confirm("是否删除?", operation);
        };

        // 搜索按钮点击事件
        $('#btnSearchDetailed').click(function () {
        	HxOrderPutDetailed.search();
        });

        $('#btnAddDetailed').click(function () {
        	HxOrderPutDetailed.addDetailed();
        });
    }
});
